<?php
/**
 * 工资汇总控制器
 */

namespace app\admin\controller;

use app\common\model\Department;
use app\common\model\Insure;
use app\common\model\Position;
use app\common\model\SalaryLog;
use think\console\Table;
use think\Db;
use think\Request;
use app\common\model\SalaryTotalDatas;

use app\common\validate\SalaryTotalDatasValidate;

class SalaryTotalDatasController extends Controller
{

    //列表
    public function index(Request $request, SalaryTotalDatas $model)
    {
        $param = $request->param();
        $where1 = '';
        $where2 = '';
        //字段条件查询
        if (isset($param['salary_time']) && $param['salary_time'] != '') {
            $salary_time = strtotime($param['salary_time']);
            $where1 .= ' and sa.salary_time=' . $salary_time;
        }else{
            $salary_time = strtotime(date('Y-m-01') . " - 1 month");
        }

        if (isset($param['department_id']) && $param['department_id'] != '') {
            $where2 .= ' and de.id=' . $param['department_id'];
        }

        $where1 .= ' and sa.delete_time =0';

        //排序
        $orderfield = isset($param['_order']) ? $param['_order'] : '';
        $by = $param['_by'] ?? '';
        $order = $orderfield . ' ' . $by;

        if ($order == ' ') {
            $order = 'de.id desc';
        }

        $model = Db::table('department de')->field(
            '
                sa.id as id,
                de.name as department_name,
                de.id as department_id,
                sa.department_id as sadepartment_id,
                sa.salary_total_json,
                sa.salary_time,
                sa.update_time
            '
        )->join('salary_total_datas sa', 'de.id = sa.department_id' . $where1, 'left')->where('de.delete_time =0 ' . $where2)->order($order);


        //查询社保关系表确定表头及渲染数据
        $insure_datas = Insure::column('insure','id');
        $insure_data = [];

        foreach ($insure_datas as $key => $value) {
            $insure_data['insure'.$key]= $value;
        }
        $insure_data['staff_count'] = '人数';
        $insure_data['personal_pay_total'] = '无保险';
        $insure_data['department_total'] = '合计';
        $header1 = ['ID', '部门', '工资日期', '更新时间',];
        $header = array_merge($header1,$insure_data);
        $header = array_values($header);
        if (isset($param['export_data']) && $param['export_data'] == 1) {
            $body = [];
            $data = $model->select();
            foreach ($data as $item) {
                $record = [];
                $record['id'] = isset($item['id'])?$item['id']:'';
                $record['department_name'] = $item['department_name'];
                $record['salary_time'] = isset($item['salary_time'])?date("Y-m",$item['salary_time']):'';
                $record['update_time'] = isset($item['update_time'])?date("Y-m-d H:i:s",$item['update_time']):'';
                if ($item['salary_total_json']){
                        $salary_total_json = json_decode($item['salary_total_json'],true);
                        //没有数据为0
                        foreach ($insure_data as $k=>$v){
                            if (isset($salary_total_json[$k])){
                                $record[$k] = $salary_total_json[$k];
                            }else{
                                $record[$k] = 0;
                            }
                        }
                    }else{
                        foreach ($insure_data as $k=>$v){
                            $record[$k] ='';
                        }
                }
                $body[] = $record;
            }
            return $this->exportData($header, $body, $param['salary_time'].'工资汇总-' . date('Y-m-d-H-i-s'));
        }
//        dump($insure_data);die;
        $data = $model->paginate($this->admin['per_page'], false, ['query' => $request->get()]);
        foreach ($data as $key => $value){
            //存在json数据
            if ($value['salary_total_json']){
                $temp = $value;
                $temp['salary_total_json'] = [];
                $salary_total_json = json_decode($value['salary_total_json'],true);
                //没有数据为0
                foreach ($insure_data as $k=>$v){
                    if (isset($salary_total_json[$k])){
                        $temp['salary_total_json'][$k] =$salary_total_json[$k];
                    }else{
                        $temp['salary_total_json'][$k] = 0;
                    }
                }
                $data[$key] = $temp;
            }else{
                $temp = $value;
                $temp['salary_time'] = $salary_time;
                $temp['salary_total_json'] = [];
                foreach ($insure_data as $k=>$v){
                    $temp['salary_total_json'][$k] ='';

                }
                $data[$key] = $temp;
            }
        }
        //关键词，排序等赋值
        $this->assign($request->get());
        //关键词，排序等赋值
        if (isset($param['department_id']) && !empty($param['department_id'])) {
            $demodel = Department::get($param['department_id']);
            $this->assign('department_list', $this->getSelectList($demodel, $param['department_id']));
        } else {
            $this->assign('department_list', $this->getSelectList(new Department));
        }
        $this->assign([
            'data' => $data,
            'page' => $data->render(),
            'total' => $data->total(),
            'insure_data' =>$insure_data,
        ]);
        return $this->fetch();
    }

    //一键生成
    public function totals(Request $request,Department $department,SalaryTotalDatas $salaryTotalDatas)
    {
        $salary_time = $request->param('salary_time');
        if ($salary_time){
            $salary_time = strtotime($salary_time);
            //所有部门id
            $department_ids =$department->column('id');
            //汇总表里已存在id修改
            $department_id1 = $salaryTotalDatas->where('salary_time',$salary_time)->column('department_id','id');
            //待处理插入
            $department_id2 = array_diff($department_ids,$department_id1);
            foreach ($department_id1 as $key => $value){
                self::compose($value,$salary_time,$key);
            }
            foreach ($department_id2 as $key => $value){
                self::compose($value,$salary_time);
            }
            return json_encode(['code'=>1,'msg'=>'success']);
        }else{
            error('缺少时间参数');
        }
    }

    //修改
    public function edit(Request $request)
    {
        $params = $request->param();
        $department_id = $params['department_id'];
        $salary_time = $params['salary_time'];
        $id = $params['id'];
        if ($department_id && $salary_time && $id){
            return json_encode(self::compose($department_id,$salary_time,$id));

        }else{
            error('缺少参数');
        }
    }

    //统计每部门数据合计方法
    public function total(Request $request)
    {
        $params = $request->param();
        $department_id = $params['department_id'];
        $salary_time = $params['salary_time'];
//        $departInfo = SalaryTotalDatas::where($params)->find();
//        dump($departInfo);die;

        return json_encode(self::compose($department_id,$salary_time));
    }

    private static function compose($department_id,$salary_time,$id='')
    {
        if ($department_id !=1){
            //各部门
            $where = ['department_id'=>$department_id,'salary_time'=>$salary_time,'delete_time'=>0,'status'=>1];
        }else{
            //公司汇总
            $where = ['salary_time'=>$salary_time,'delete_time'=>0,'status'=>1];
        }
        $datas = Db::table('salary_log')->field('insure_id,social_security_salary,personal_pay')->where($where)->select();
        $data = [];
        $data['staff_count'] = count($datas);
        $data['personal_pay_total'] = 0;
        $data['department_total'] = 0;
        if ($datas){
            foreach ($datas as $key => $value){
                $data[$value['insure_id']][] = $value['social_security_salary'];
                $data['personal_pay_total'] +=$value['personal_pay'];
                $data['department_total'] +=$value['personal_pay']+$value['social_security_salary'];
            }
            $data['personal_pay_total'] =round($data['personal_pay_total'],2);
            $data['department_total'] =round($data['department_total'],2);
            foreach ($data as $key => $value){
                if (is_array($value)){
                    $vs =0;
                    foreach ($value as $v){
                        $vs +=$v;
                    }
                    unset($data[$key]);
                    $data['insure'.$key] = $vs;
                }
            }
        }
        $insertData['salary_total_json']    = json_encode($data,JSON_UNESCAPED_UNICODE);
        $insertData['salary_time']          = $salary_time;
        $insertData['department_id']        = $department_id;
        $insertData['create_time']          =$_SERVER['REQUEST_TIME'];
        $insertData['update_time']          =$_SERVER['REQUEST_TIME'];
        $salaryTotalDatas = new SalaryTotalDatas();
        if (!$id){
            $result = $salaryTotalDatas->save($insertData);
            $returnData['id'] = $salaryTotalDatas->id;
        }else{
            $result = $salaryTotalDatas->save($insertData,['id'=>$id]);
            $returnData['id'] = $id;
        }
        $returnData['salary_time'] = date('Y-m',$salary_time);
        $returnData['update_time'] = date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME']);
        $returnData['salary_total'] = $data;
        $returnData['department_id'] = $department_id;

        return $result ? ['code'=>1,'msg'=>'添加成功','data'=>$returnData] : ['code'=>0,'msg'=>'操作失败'];
    }


    //防止重复
    public function uniqueTotal(Request $request, SalaryTotalDatas $salaryTotalDatas)
    {
        $data = SalaryTotalDatas::where($request->param())->find();

        if ($data){
            return json_encode(['code'=>0,'msg'=>'已经有此部门汇总信息','data'=>['id'=>$data['id']]]);
        }else{
            return json_encode(['code'=>1,'msg'=>'success']);
        }
    }

    //删除
    public function del($id, SalaryTotalDatas $model)
    {
        if (count($model->noDeletionId) > 0) {
            if (is_array($id)) {
                if (array_intersect($model->noDeletionId, $id)) {
                    return error('ID为' . implode(',', $model->noDeletionId) . '的数据无法删除');
                }
            } else if (in_array($id, $model->noDeletionId)) {
                return error('ID为' . $id . '的数据无法删除');
            }
        }

        if ($model->softDelete) {
            $result = $model->whereIn('id', $id)->useSoftDelete('delete_time', time())->delete();
        } else {
            $result = $model->whereIn('id', $id)->delete();
        }

        return $result ? success('操作成功', URL_RELOAD) : error();
    }

}
